#include "app.h"
#include "delay.h"
#include "LCD_CFG.h"
#include "LCD_CTRL_LIB.h"
#include "gui_guider.h"
#include "key_scan.h"
#include "timeout.h"
#include "nrf_process.h"
#include "sfud.h"
#include "user_cfg.h"
#include "events_init.h"

app_para_t app_para;
lv_ui guider_ui;
RCC_ClocksTypeDef clocks;
unsigned int counter = 100;
uint16_t test_buf[1] = {0}, power_buf[1] = {0};
void flash_dump(uint32_t addr, uint16_t len);

extern key_u32_t key_clk;


//定时器3中断服务程序
void TIM3_IRQHandler(void)   //TIM3中断  1ms
{
    static uint16_t flag, cnt = 0;
    static uint32_t low_cnt;
	if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)  //检查TIM3更新中断发生与否
	{
		TIM_ClearITPendingBit(TIM3, TIM_IT_Update);  //清除TIMx更新中断标志
        lv_tick_inc(1); // LVGL时基
        key_clk++;
        TimeOut_Det_DecHandle();
        Pair_Long_Handle();
        if (++cnt >= 5) {
            cnt = 0;
            lv_timer_handler();
        }

	}
}


void EXTI9_5_IRQHandler(void)
{
	if(EXTI_GetITStatus(EXTI_Line6) == SET)
	{
		EXTI_ClearITPendingBit(EXTI_Line6);
	}

    if(EXTI_GetITStatus(EXTI_Line7) == SET)
	{
		EXTI_ClearITPendingBit(EXTI_Line7);
	}
    if(EXTI_GetITStatus(EXTI_Line8) == SET)
	{
		EXTI_ClearITPendingBit(EXTI_Line8);
	}

    if(EXTI_GetITStatus(EXTI_Line9) == SET)
	{
		EXTI_ClearITPendingBit(EXTI_Line9);
	}
}

void EXTI15_10_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line11) == SET) {
        EXTI_ClearITPendingBit(EXTI_Line11);
    }


	if(EXTI_GetITStatus(EXTI_Line10) == SET)
	{
		EXTI_ClearITPendingBit(EXTI_Line10);
	}


    if(EXTI_GetITStatus(EXTI_Line12) == SET)
	{
        EXTI_ClearITPendingBit(EXTI_Line12);
	}
}


void EXTI1_IRQHandler(void)
{
	EXTI_InitTypeDef EXTI_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOC|RCC_APB2Periph_GPIOD|\
							RCC_APB2Periph_GPIOE|RCC_APB2Periph_GPIOF|RCC_APB2Periph_GPIOG,ENABLE);

	EXTI_ClearITPendingBit(EXTI_Line1);

    if (EXTI_GetITStatus(EXTI_Line1) == SET) {
        if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)) {
            EXTI_InitStructure.EXTI_Line = EXTI_Line1;
            EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
            EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
            EXTI_InitStructure.EXTI_LineCmd = ENABLE;
            EXTI_Init(&EXTI_InitStructure);
        } else {
            EXTI_ClearITPendingBit(EXTI_Line1);
            EXTI_InitStructure.EXTI_Line = EXTI_Line1;
            EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
            EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
            EXTI_InitStructure.EXTI_LineCmd = ENABLE;
            EXTI_Init(&EXTI_InitStructure);
        }

        EXTI_ClearITPendingBit(EXTI_Line1);
    }
}


void App_Init(void)
{
    RCC_ClkConfiguration();
    MHFLASH_Read(MH_FLASH_POWER, (uint16_t*)(power_buf), 1);

    Test_Gpio_Init();
    Delay_Init();
    TIM3_Configuration();
    UART_Configuration(256000);
    #if 1
    Key_Init();
    TimeOut_Det_Init();
    Nrf_Process_Init();
    ADC_Configuration();
    Charge_Deteciton();
    #endif

    #if 1
    W25QXX_Init();
    // if (W25QXX_ReadID() != W25Q128)								//检测不到
	// {
	// 	printf("W25Q128 Check Error!\n");
	// 	printf("Read ID: 0x%x\n",W25QXX_ReadID());
	// } else {
    //     printf("W25Q128 Check Succeed!\n");
	// 	printf("Read ID: 0x%x\n",W25QXX_ReadID());
    // }

    lv_init();                     // LVGL初始化
    lv_port_disp_init();           // LVGL显示初始化
    lv_port_fs_init();             // LVGL文件系统初始化
    lv_port_indev_init();          // LVGL输入设备初始化
    setup_ui(&guider_ui);
   	events_init(&guider_ui);
    // Wwdg_Init();

    printf("starting success !");
    #else

    //flash_dump(MOTION_FOOT_ADDR, MOTION_FOOT_LEN);
    #endif

    if (power_buf[0] != 0xFFFF) {
        Enter_LowPowerMode();
    }

    Delay_Ms(80);

    MHFLASH_Read(FLASH_BACKLIGHT_ADDR, (uint16_t*)(test_buf), 1);
    counter = test_buf[0];
    if (counter > 100) {
        counter = 100;
    }
    Lcd_Backlight_Pwm(counter);
    memset(&app_para, 0, sizeof(app_para_t));
    app_para.cur_mode = RUNNING_MODE;
    app_para.work_sta = true;
    TimeOut_Record(&app_para.tout.sleep_tout, SLEEP_TIMEOUT);

    nrf_para.nrf.stop_send_flag = true;
    TimeOut_Record(&nrf_para.tout.release_tout, 300);
    Wdt_Init();
}


void App_Handle(void)
{
    IWDG_ReloadCounter();
    // WWDG_SetCounter(0x70);
    Nrf_Process();
    if (TimeOut_Det_Check(&app_para.tout.adc_power_tout)) {
        TimeOut_Record(&app_para.tout.adc_power_tout, 500);
        ADC_SoftwareStartConvCmd(ADC1, ENABLE);
    }

    if (nrf_para.pair_ui_back && TimeOut_Det_Check(&nrf_para.tout.pair_ui_back_tout)) {
        nrf_para.pair_ui_back = 0;
        ui_load_scr_animation(&guider_ui, &guider_ui.main, guider_ui.main_del, NULL, setup_scr_main, LV_SCR_LOAD_ANIM_NONE, 0, 0, false, true);
    }

    if (app_para.power_low_flag && TimeOut_Det_Check(&app_para.tout.power_low_ui_back_tout)) {
        app_para.power_low_flag = 0;
        ui_load_scr_animation(&guider_ui, &guider_ui.main, guider_ui.main_del, NULL, setup_scr_main, LV_SCR_LOAD_ANIM_NONE, 0, 0, false, true);
    }
    if (app_para.cur_mode == STOP_MODE) {
        // Enter_LowPowerMode();
        Enter_LowPower_Handle();
    } else {
        if (TimeOut_Det_Check(&app_para.tout.sleep_tout)) {
            app_para.cur_mode = STOP_MODE;
            app_para.work_sta = true;
        }
    }

    if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_1)) {
        app_para.charge_flag = true;
    } else {
        app_para.charge_flag = false;
    }
}


void flash_dump(uint32_t addr, uint16_t len)
{
    uint8_t buf[16];
    uint16_t i, j;

    printf("\r\nFlash dump from 0x%08X, length: %d bytes\r\n", addr, len);

    for(i = 0; i < len; i += 16)
    {
        // 读取16字节数据
        W25QXX_Read(buf, addr + i, (len-i)>=16 ? 16 : (len-i));

        // 打印地址
        printf("0x%08X: ", addr + i);

        // 打印十六进制数据
        for(j = 0; j < 16; j++)
        {
            if((i + j) < len)
            {
                printf("%02X ", buf[j]);
            }
            else
            {
                printf("   ");
            }
        }

        // 打印ASCII字符
        printf(" |");
        for(j = 0; j < 16; j++)
        {
            if((i + j) < len)
            {
                if(buf[j] >= 0x20 && buf[j] <= 0x7E)
                {
                    printf("%c", buf[j]);
                }
                else
                {
                    printf(".");
                }
            }
            else
            {
                printf(" ");
            }
        }
        printf("|\r\n");
    }
}




